import 'package:fish_redux/fish_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hayll_app_village_master/hayll/network/yll_network.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_acceess_card_component/bean/village_access_card_response.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_simple_component/action.dart';
import 'package:hayll_app_village_master/hayll/village_manager/network/village_action.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'action.dart';
import 'state.dart';

Effect<VillageAcceessCardState> buildEffect() {
  return combineEffects(<Object, Effect<VillageAcceessCardState>>{
    VillageAcceessCardAction.action: _onAction,
    Lifecycle.initState: _requestCards,
    VillageSimpleAction.chooseHouseChanged: _requestCards,
  });
}

void _onAction(Action action, Context<VillageAcceessCardState> ctx) {}

void _requestCards(Action action, Context<VillageAcceessCardState> ctx) async {
  var sp = await SharedPreferences.getInstance();
  var lastVillageId = sp.getInt('lastVillage');
  var params = {
    'villageId': lastVillageId,
    'ownerName': '',
    'cardNo': '',
    'roomCode': '',
    'cardTypes': '',
    'cardStatus': '',
    'createTime': '',
    'pageNum': 1,
    'pageSize': 20,
  };
  if (ctx.state.unit != null && ctx.state.unit.itemId > 0) {
    params['targetId'] = ctx.state.unit.itemId;
    params['targetType'] = 3; //1:小区 2：楼栋 3：单元
  } else if (ctx.state.build != null && ctx.state.build.buildingId > 0) {
    params['targetId'] = ctx.state.build.buildingId;
    params['targetType'] = 2; //1:小区 2：楼栋 3：单元
  } else {
    params['targetId'] = lastVillageId;
    params['targetType'] = 1; //1:小区 2：楼栋 3：单元
  }

  YllNetwork.requestPost(VillageAction.getAccessCards, params: params,
      success: (json) {
    ctx.state.cardList.clear();
    var result = VillageAccessCardInfoListResult.fromJson(json);
    if (result.data != null) {
      ctx.state.cardList.addAll(result.data);
    }
    ctx.dispatch(VillageAcceessCardActionCreator.refreshUI());
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}
